/**
 * 导入导出的JSON数据到MongoDB
 * 专门用于导入 exported-data 目录中的数据
 */

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

console.log('📥 开始导入导出的JSON数据到MongoDB...');
console.log('');

// 检查导出数据目录
const exportedDataDir = path.join(__dirname, 'exported-data');

if (!fs.existsSync(exportedDataDir)) {
  console.error('❌ 未找到 exported-data 目录');
  console.log('💡 请先运行: npm run export-data');
  process.exit(1);
}

// 检查关键文件
const requiredFiles = [
  'users.json',
  'medical-equipment.json',
  'departments.json'
];

const missingFiles = requiredFiles.filter(file => 
  !fs.existsSync(path.join(exportedDataDir, file))
);

if (missingFiles.length > 0) {
  console.error('❌ 缺少必要的数据文件:', missingFiles.join(', '));
  console.log('💡 请先运行: npm run export-data');
  process.exit(1);
}

console.log('✅ 发现导出数据文件:');
const files = fs.readdirSync(exportedDataDir);
files.forEach(file => {
  const filePath = path.join(exportedDataDir, file);
  const stats = fs.statSync(filePath);
  const sizeKB = (stats.size / 1024).toFixed(2);
  console.log(`  - ${file} (${sizeKB} KB)`);
});

console.log('');
console.log('🚀 开始导入数据...');

// 运行迁移脚本
const migrationScript = 'migrate-simple.js';

const child = spawn('node', [migrationScript], {
  stdio: 'inherit',
  cwd: __dirname
});

child.on('close', (code) => {
  if (code === 0) {
    console.log('');
    console.log('🎉 数据导入完成！');
    console.log('');
    console.log('🔗 验证导入结果:');
    console.log('  GET http://localhost:8080/v1/mongodb/connection');
    console.log('  GET http://localhost:8080/v1/mongodb/users');
    console.log('  GET http://localhost:8080/v1/mongodb/alerts');
    console.log('');
    console.log('🔑 测试账号 (从 users-with-passwords.json):');
    
    // 读取并显示测试账号
    try {
      const usersWithPasswords = path.join(exportedDataDir, 'users-with-passwords.json');
      if (fs.existsSync(usersWithPasswords)) {
        const users = JSON.parse(fs.readFileSync(usersWithPasswords, 'utf-8'));
        users.slice(0, 3).forEach(user => {
          console.log(`  - ${user.username} / ${user.plainPassword} (${user.role})`);
        });
      }
    } catch (error) {
      console.log('  查看 exported-data/users-with-passwords.json 获取账号信息');
    }
  } else {
    console.error(`❌ 数据导入失败，退出码: ${code}`);
  }
});

child.on('error', (error) => {
  console.error('❌ 启动导入脚本失败:', error);
});